package bajo.src;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.UiApplication;

public class HTTPDataThread extends Thread{
//	
//	public static byte[] global_data = new byte[0]; // used to pass data
//	public static Object global_lock = new Object(); // used as lock

	private CallBack functionObject;
	
	private String url; // the address to connect
	private URLEncodedPostData data = null; // used to send data
	private HttpConnection conn = null; // http connection handler
	private String httpConnectionType; // type of the http connection. This is either POST or GET
	private boolean writeServer = false; // decides if server is waiting for our input
	private final int BUFSIZE = 10000; // used when reading from the server
	
	private boolean run = false;
	
	/* Constructor */
	public HTTPDataThread(String newUrl, URLEncodedPostData data, String httpConnectionType, CallBack function, boolean run) {
		this.functionObject = function;
		url = newUrl;
		this.data = data;
		this.httpConnectionType = httpConnectionType;  
		this.writeServer = (HttpConnection.POST == httpConnectionType);  
		this.run = run;
	}

	public void run() {
		// start the connection
		try {
			conn = (HttpConnection) Connector.open(url + Constants.WIFI_INTERFACE, Connector.READ_WRITE);
			
			// TODO: check the responseCode
			conn.setRequestMethod(httpConnectionType);
			
			// we have data to send to server
			if (data != null && this.writeServer){
				if (data.size() < 1)
					return; // nothing to send just return
				// parse the given data so we can send it
				byte[] dataBytes = data.getBytes();
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				conn.setRequestProperty("Content-Length", (new Integer(dataBytes.length)).toString());
				OutputStream outputStream = conn.openOutputStream();
				outputStream.write(dataBytes);
				outputStream.flush();
				outputStream.close();
			}
			
			// read stuff from the server
			if (conn.getResponseCode() == HttpsConnection.HTTP_OK){
				InputStream inputStream = conn.openInputStream();
				
				byte[] retData = new byte[BUFSIZE];
				int length = 0;
				// used to append the downloaded raw data
				StringBuffer rawResponse = new StringBuffer();
				while ((length = inputStream.read(retData)) != -1){
					rawResponse.append(new String(retData, 0, length));
				}				
				// get the combined data
				byte[] resultData = rawResponse.toString().getBytes();
				
				final String[] resultDataString = split(new String(resultData));
				// call back the function given
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run(){
						functionObject.function(resultDataString);
					}
				});			
				
//				synchronized(HTTPDataThread.global_lock){
//					global_data = new byte[resultData.length];
//					System.arraycopy(resultData, 0, global_data, 0, resultData.length); 
//				}
				inputStream.close();
			}
		
			// close the connection
			if (conn != null)
				conn.close();			
		} catch (IOException e) {
//			String t = this.url;
//			byte[] resultData = t.getBytes();
//			global_data = new byte[resultData.length];
//			System.arraycopy(resultData, 0, global_data, 0, resultData.length); 
		}
	}
	
	/* Copy the data to a global variable */
//	public static String[] copyData (){
//		byte[] retData = new byte[global_data.length];
//		System.arraycopy(global_data, 0, retData, 0, global_data.length);
//		String[] result = split(new String(retData));
//		return result;
//	}
	
	/* Parse the received data into an array of Strings where each element represents a line of String. */
	public static String[] split(String str){
		Vector v = new Vector();
		String seperator = "\r\n";
		int iStart =0;
		int iEnd = str.indexOf(seperator);
		
		if (iEnd != -1){
			while(iEnd != -1){
				String s = str.substring(iStart,iEnd );
				if(s.length()>0){
					v.addElement(s);
				}
				iStart = iEnd + seperator.length();
				iEnd = str.indexOf(seperator,iStart);
			}
			if(iStart != str.length()){
				String s = str.substring(iStart);
				if(s.length()>0){
					v.addElement(s);
				}
			}
		}else{
			if(str.length()>0){
				v.addElement(str);
			}
		}
		String[] result = new String[v.size()];
		v.copyInto(result);
		return result;	
	}

}
